import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_user.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/user/osc_user_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SearchUser extends StatefulWidget{
  final String keyword;
  const SearchUser({Key key, this.keyword}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new SearchUserState();
  }
}

class SearchUserState extends State<SearchUser> with SingleTickerProviderStateMixin{

  TextEditingController editingController;
  FocusNode fnKeyword;

  HttpRepository httpRepository;
  String pageToken;

  String keyword;

  bool isLoadData = false;

  int userSize = 0;
  List<OscUser> users;

  RefreshController refreshController;

  @override
  void initState() {
    super.initState();
    keyword = widget.keyword;
    editingController = new TextEditingController(text: keyword);
    refreshController = RefreshController(initialRefresh: true);
    fnKeyword = FocusNode();
    httpRepository = new HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    editingController?.dispose();
    refreshController.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildBar(),
      body: buildBody(),
    );
  }

  buildBar(){
    return PreferredSize(
      child: AppBar(
        titleSpacing: Dimens.gap_view_big,
        title: buildSearch(),
      ),
      preferredSize: Size.fromHeight(Dimens.view_tab_bar_height),
    );
  }

  Widget buildSearch(){
    return Row(
      children: <Widget>[
        Expanded(
          child: Container(
            margin: EdgeInsets.symmetric(vertical: Dimens.gap_view_small),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: Colors.black12, width: Dimens.gap_divider_height_smallest),
              borderRadius: BorderRadius.circular(Dimens.view_radius_size_biggest),
            ),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: editingController,
                    focusNode: fnKeyword,
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(Dimens.gap_view_bigger),
                      prefixIcon: Icon(Icons.search, color: Colors.black26,),
                      border: buildTextFieldBorder(),
                      focusedBorder: buildTextFieldBorder(),
                      enabledBorder: buildTextFieldBorder(),
                      disabledBorder: buildTextFieldBorder(),
                      errorBorder: buildTextFieldBorder(),
                      focusedErrorBorder: buildTextFieldBorder(),
                      hintStyle: MyTextStyle.TEXT_FIELD_COMMENT_HINT,
                      hintText: "搜索用户",
                    ),
                    style: MyTextStyle.TEXT_FIELD_COMMENT,

                    inputFormatters: [LengthLimitingTextInputFormatter(18)],
                    textInputAction: TextInputAction.search,
                    onChanged: (text){
                      setState(() {
                        keyword = text;
                      });
                    },
                    onSubmitted: (text){
                      keyword = text;
                      refresh();
                    },
                  ),
                ),
                IconButton(
                  icon: Icon(
                    Icons.clear,
                    color: StringUtil.isEmpty(editingController.text)? Colors.transparent : Colors.black26,),
                  onPressed: (){
                    setState(() {
                      editingController.clear();
                    });
                  },
                ),
              ],
            ),
          ),
        ),
        SmallWidgets.buildAction(
            textColor: Colors.green,
            data: "搜索",
            onTap: (){
              refresh();
            }
        ),
      ],
    );
  }

  buildTextFieldBorder(){
    return InputBorder.none;
  }

  buildBody(){
    return SmartRefresher(
      controller: refreshController,
      enablePullUp: true,
      onLoading: loadData,
      onRefresh: refresh,
      child: buildListView(),
    );
  }

  buildListView(){
    return ListView.separated(
      itemBuilder: (BuildContext context, int index) {
        if (userSize == 0) {
          return NoDataWidget();
        } else {
          return OscUserWidget(user: users.elementAt(index));
        }
      },
      separatorBuilder: (BuildContext context, int index) {
        return Divider(height: Dimens.gap_divider_height_smallest,);
      },
      itemCount: isLoadData && userSize == 0? 1 : userSize,
    );
  }

  refresh() async{
    pageToken = null;
    userSize = 0;
    users?.clear();
    await loadData();
  }

  loadData() async{
    await httpRepository.searchUser(keyword: keyword, pageToken: pageToken).then((resp){
      if(resp != null){
        if(resp.success && resp.result != null){
          OscBaseListResult<OscUser> result = resp.result;
          if(pageToken == null){
            users = result.items;
          } else {
            users.addAll(result.items);
          }
          pageToken = result.nextPageToken;
          userSize = users?.length??0;
          if(result.requestCount > result.responseCount){
            refreshController.loadNoData();
          } else {
            refreshController.loadComplete();
          }
          refreshController.refreshCompleted();
          if (mounted) {
            setState(() {

            });
          }
        }
      }
    });
  }


  jump2Page(Widget page){
    NavigatorUtil.pushPage(context, page);
  }

  showToast(String msg){
    PdUtil.showToast(msg: msg);
  }

}